from http.server import BaseHTTPRequestHandler, HTTPServer
# 定义处理请求的类
from urllib.parse import parse_qs

from Config import Config


class CustomHTTPServer(HTTPServer):
    def __init__(self, server_address, RequestHandlerClass):
        super().__init__(server_address, RequestHandlerClass)
        self.handler_instance = RequestHandlerClass


class MyHTTPRequestHandler(BaseHTTPRequestHandler):
    # 处理POST请求的方法
    def do_POST(self):
        if self.path == '/' + Config.modleName + '/add':
            self.handle_add()
        elif self.path == '/' + Config.modleName + '/remove':
            self.handle_remove()
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not Found')

    def handle_add(self):
        # 读取请求体中的数据
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        form_data = parse_qs(post_data)
        patientId = form_data.get('patientId', [''])[0]
        Config.add_patient(patientId)

        # 设置响应状态码
        self.send_response(200)
        # 设置响应头部
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # 设置响应内容
        response = f"True"
        # 发送响应内容
        self.wfile.write(bytes(response, "utf8"))

    def handle_remove(self):
        # 读取请求体中的数据
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        form_data = parse_qs(post_data)
        patientId = form_data.get('patientId', [''])[0]
        Config.remove_patient(patientId)

        # 设置响应状态码
        self.send_response(200)
        # 设置响应头部
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # 设置响应内容
        response = f"True"
        # 发送响应内容
        self.wfile.write(bytes(response, "utf8"))